import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/types.d';
import { standardReg } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormDatePicker,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Divider, Input, message } from 'antd';
import { useState } from 'react';
import { useModel } from 'umi';
import { updatePatrolDevice } from '../service';
import type { CreatePatrolDeviceType, PatrolDeviceTableItem } from '../types.d';
import { DEFAUT_DEVICEMODEL } from '../types.d';
// const UPDATE_MANFACTURER = [...DEFAUT_MANUFACTURER];
const UPDATE_DEVICEMODEL = [...DEFAUT_DEVICEMODEL];
export default (props: { reload: () => void; currPatrol: PatrolDeviceTableItem }) => {
  const { reload, currPatrol } = props;
  const { deviceModel: dm } = currPatrol;
  if (dm && !UPDATE_DEVICEMODEL.includes(dm)) {
    UPDATE_DEVICEMODEL.push(dm);
  }
  // if (mf && !UPDATE_MANFACTURER.includes(mf)) {
  //   UPDATE_MANFACTURER.push(mf);
  // }
  const { initialState } = useModel('@@initialState');
  const userRole = initialState?.currentUser?.role;
  // const [manuFactureOptions, setManuFactureOptions] = useState<string[]>(UPDATE_MANFACTURER);
  // const [tempMan, setTempMan] = useState<string>('');
  const [modelOptions, setModelOptions] = useState<string[]>(UPDATE_DEVICEMODEL);
  const [tempModel, setTempModel] = useState<string>('');
  const { _id, deviceSn, deviceModel, ownerId, iccid, iccidExpiredTime } = currPatrol;
  return (
    <ModalForm<CreatePatrolDeviceType>
      title="编辑巡检设备"
      layout="horizontal"
      width="40vw"
      modalProps={{
        destroyOnClose: true,
      }}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={<a>编辑</a>}
      initialValues={{
        deviceSn: deviceSn,
        // manufacturer: manufacturer,
        deviceModel: deviceModel,
        ownerId: ownerId,
        iccid: iccid,
        iccidExpiredTime: iccidExpiredTime,
      }}
      onFinish={async (values) => {
        const res = await updatePatrolDevice(_id, values);
        if (res.success) {
          message.success({
            content: res.message,
            key: 'update_patrolDevice',
          });
          reload();
          return true;
        }
        message.error({
          content: res.message,
          key: 'update_patrolDevice',
        });
        return false;
      }}
    >
      <ProFormText
        label="设备编号"
        width="xl"
        name="deviceSn"
        required
        disabled
        placeholder="请输入设备编号"
      />
      {/* <ProFormSelect
        width="xl"
        name="manufacturer"
        label="生产厂家"
        options={manuFactureOptions}
        fieldProps={{
          dropdownRender: (menu) => (
            <div>
              {menu}
              <Divider />
              <div style={{ display: 'flex', flexWrap: 'nowrap', padding: '0px 12px 8px' }}>
                <Input
                  size="small"
                  style={{ flex: 'auto' }}
                  value={tempMan}
                  onChange={(event) => setTempMan(event.target.value || '')}
                />
                <a
                  style={{ flex: 'none', padding: '4px', display: 'block', cursor: 'pointer' }}
                  onClick={() => {
                    if (tempMan) {
                      setManuFactureOptions([...manuFactureOptions, tempMan]);
                      setTempMan('');
                    }
                  }}
                >
                  <PlusOutlined /> 添加
                </a>
              </div>
            </div>
          ),
        }}
      /> */}
      <ProFormSelect
        width="xl"
        name="deviceModel"
        label="设备类型"
        options={modelOptions}
        fieldProps={{
          dropdownRender: (menu) => (
            <div>
              {menu}
              <Divider />
              <div style={{ display: 'flex', flexWrap: 'nowrap', padding: '0px 12px 8px' }}>
                <Input
                  size="small"
                  style={{ flex: 'auto' }}
                  value={tempModel}
                  onChange={(event) => setTempModel(event.target.value || '')}
                />
                <a
                  style={{ flex: 'none', padding: '4px', display: 'block', cursor: 'pointer' }}
                  onClick={() => {
                    if (tempModel) {
                      setModelOptions([...modelOptions, tempModel]);
                      setTempModel('');
                    }
                  }}
                >
                  <PlusOutlined /> 添加
                </a>
              </div>
            </div>
          ),
        }}
      />
      <ProFormText
        width="xl"
        label="流量卡号"
        placeholder="请输入流量卡号"
        name="iccid"
        rules={[
          {
            validator: (_, val) => {
              if (val && !standardReg.test(val))
                return Promise.reject(new Error('流量卡号无效，请重新输入'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormDatePicker
        width="xl"
        label="过期时间"
        placeholder="请选择日期"
        name="iccidExpiredTime"
      />
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          width="xl"
          debounceTime={300}
          label="归属公司"
          showSearch
          placeholder="请选择归属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
    </ModalForm>
  );
};
